﻿using AutoMapper;
using MD5Hash;
using MediatR;
using SmartCity.BasicData.Api.Write.Application.Command.Account;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Common.Menus;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using Yitter.IdGenerator;

namespace SmartCity.BasicData.Api.Write.Application.Handler.Account
{
    /// <summary>
    /// 添加新账号的处理类
    /// </summary>
    public class CreateAccouontHandler : IRequestHandler<CreateAccountCommand, ApiResult<int>>
    {
        private readonly ILogger<CreateAccouontHandler> logger;
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IMapper mapper;

        public CreateAccouontHandler(ILogger<CreateAccouontHandler> logger, IBaseRepository<AccountModel> accountRepo, IMapper mapper)
        {
            this.logger = logger;
            this.accountRepo = accountRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加新账号的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //校验账号是否重复
            int userCount = accountRepo.GetAsync(x => x.AccountName == request.AccountName).Result.Count();
            if (userCount>0) { //账号已经存在
                result.Code = EnumResultCode.Error;
                result.Msg = "账号已经存在";
                result.Data = userCount;
                return Task.FromResult(result);
            }


            try
            {
                //使用aotumapper组件把请求命令对象request 映射为AccountModel的对象
                AccountModel model = mapper.Map<AccountModel>(request);
                model.Id = YitIdHelper.NextId();
                model.AccountPass = model.AccountPass.GetMD5();//密码Md5加密
                int i = accountRepo.CreateAsync(model).Result;

                if (i > 0)
                {
                    result.Code = EnumResultCode.Success;
                    result.Msg = "添加新账号成功";
                    result.Data = i;
                }
                else
                {
                    result.Code = EnumResultCode.Fail;
                    result.Msg = "添加新账号失败";
                    result.Data = i;
                }
            }
            catch (Exception e)
            {
                logger.LogError("发生未知异常:"+e.Message);
            }

            
            return Task.FromResult(result);
        }
    }
}
